package com.bilibili.sys.servlet;

import com.bilibili.sys.utils.Constant;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * @author alpha
 * @program: BookSystem
 * @description: 处理文件上传的Servlet
 * @since 2024-03-26 17:10
 **/
@WebServlet(name = "uploadServlet",urlPatterns = {"/sys/uploadServlet"})
public class UploadServlet extends HttpServlet {
    /**
     * 文件上传处理的方法
     * @param req
     * @param resp
     * @return void
     * @author alpha
     * @since 2024/03/26 17:12
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //上传的文件信息
        String uploadPath = Constant.UPLOAD_DIRECTORY;
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        //做文件上传的处理
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //可以通过ServletFileUpload对上传过来的请求做解析
        //FileItem其实就是客户端表单提交的各个表单领域的内容
        try{
            List<FileItem> fileItems = upload.parseRequest(req);
            if(fileItems!=null && fileItems.size()>0){
                //说明有表单信息提交
                for (FileItem fileItem : fileItems) {
                    //判断当前获取的信息是否为文件
                    if(!fileItem.isFormField()){
                        //表示获取的是上传的文件信息，而非文本信息
                        //获取上传文件的名称
                        String fileName = new File(fileItem.getName()).getName();
                        //客户端上传的文件我们需要在本地重新生成新的文件名称
                        fileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
                        //拼接完整的文件上传的路径
                        String filePath = uploadPath+File.separator+fileName;
                        System.out.println("filePath = " + filePath);
                        //然后把上传后的文件存储到磁盘中
                        fileItem.write(new File(filePath));
                        //需要把生成的文件名称返回给客户端
                        PrintWriter writer = resp.getWriter();
                        writer.write(fileName);
                        writer.flush();
                        writer.close();
                    }
                }
            }
        }catch (Exception e){

        }
    }
}
